package com.hulman.oms.service;

import com.hulman.oms.bean.ElectricMeter;
import com.hulman.oms.bean.Result;
import com.hulman.oms.bean.WaterMeter;
import com.hulman.oms.bean.WaterReportItem;
import com.hulman.oms.dao.WaterReportItemDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author: maxwellens
 */
@Service
public class WaterReportItemService
{
    @Autowired
    private WaterReportItemDao waterReportItemDao;
    @Autowired
    private WaterMeterService waterMeterService;

    public List<WaterReportItem> findWaterReportItems(Map<String, Object> map)
    {
        return waterReportItemDao.findWaterReportItems(map);
    }


    public List<WaterReportItem> findWaterReportItemsByReportId(Integer reportId)
    {
        Map<String, Object> map = new HashMap<>();
        map.put("reportId", reportId);
        return waterReportItemDao.findWaterReportItems(map);
    }

    public Integer findWaterReportItemsCount(Map<String, Object> map)
    {
        return waterReportItemDao.findWaterReportItemsCount(map);
    }

    public Result findWaterReportItemsResult(Map<String, Object> map)
    {
        Integer page = (Integer) map.get("page");
        Integer limit = (Integer) map.get("limit");
        if (page != null && limit != null)
        {
            map.put("start", (page - 1) * limit);
            map.put("length", limit);
        }
        int count = waterReportItemDao.findWaterReportItemsCount(map);
        List<WaterReportItem> data = waterReportItemDao.findWaterReportItems(map);
        return new Result(data, count);
    }

    public WaterReportItem findWaterReportItemById(Integer id)
    {
        return waterReportItemDao.findWaterReportItemById(id);
    }

    public void saveWaterReportItem(WaterReportItem waterReportItem)
    {
        if (waterReportItem.getId() != null && waterReportItem.getId() != 0)
        {
            waterReportItemDao.updateWaterReportItem(waterReportItem);
        } else
        {
            waterReportItemDao.insertWaterReportItem(waterReportItem);
        }
    }

    public void deleteWaterReportItemById(Integer id)
    {
        waterReportItemDao.deleteWaterReportItemById(id);
    }

    public void deleteWaterReportItems(int[] ids)
    {
        waterReportItemDao.deleteWaterReportItems(ids);
    }

    public void read(WaterReportItem waterReportItem)
    {
        //更新明细
        waterReportItem.setState(1);
        waterReportItem.setReadTime(new Date());
        saveWaterReportItem(waterReportItem);
        //更新水表信息
        WaterMeter meter = waterMeterService.findWaterMeterById(waterReportItem.getMeterId());
        if (meter != null)
        {
            meter.setAmount(waterReportItem.getThisAmount());
            meter.setReadTime(new Date());
            waterMeterService.saveWaterMeter(meter);
        }
    }

}
